define([
    'app',
    'moment-timezone',
    'rcss!css/clock',
    'bootstrap-datetimepicker'
], function(app, moment) {
    app.controller('TimestampHelperController', function($scope, $compile, $timeout, xUtil) {
        var self = this;
        self.date = '';
        self.time = '';
        self.nowTimestamp = '';
        self.stop = false;

        const defaultFormat = 'YYYY-MM-DD HH:mm:ss.SSS';
        self.format = '';
        self.custFormat = defaultFormat;

        self.datetime = null;
        self.timestamp = null;
        self.timestampUnit = 'ms';
        self.timezone = 'Asia/Shanghai';
        self.timezones = moment.tz.names();

        var jqDatetimePicker = null;

        self.init = function() {
            xUtil.clipboard.copy('#copy', function() {
                return self.nowTimestamp;
            });

            // Clock
            (function() {
                var hour = $('.pointer.hour'),
                    minute = $('.pointer.minute'),
                    second = $('.pointer.second');
                (function loop() {
                    setTimeout(loop, 1000 / 12);
                    draw();
                })();
                function draw() {
                    var now = moment().tz(self.timezone),
                        seconds = now.seconds(),
                        minutes = now.minutes(),
                        hours = now.hours();
                    rotate(second, seconds * 6 - 90);
                    rotate(minute, minutes * 6 - 90);
                    rotate(hour, (hours % 12) * 30 + minutes * 30 / 60 - 90);
                    $timeout(function() {
                        self.date = now.format('YYYY/MM/DD');
                        self.time = now.format('HH:mm');
                        if (!self.stop) {
                            self.nowTimestamp = now.format('x');
                        }
                    });
                }
                function rotate(target, degree) {
                    target.css({
                        'transform': 'rotate(' + degree + 'deg)',
                        '-moz-transform': 'rotate(' + degree + 'deg)',
                        '-webkit-transform': 'rotate(' + degree + 'deg)'
                    });
                }
            })();

            jqDatetimePicker = $('#datetime-picker');
            // Datetime picker
            (function() {
                jqDatetimePicker.datetimepicker({
                    //locale: moment.locale('zh-CN'),
                    format: self.custFormat,
                    showTodayButton: true,
                    showClear: true,
                    useCurrent: false
                }).on('dp.change', function(event) {
                    $timeout(function() {
                        self.datetime = event.date;
                    });
                });
            })();
        }

        self.changeTimezone = function(timezone) {
            jqDatetimePicker.data('DateTimePicker').timeZone(timezone);
            self.changeFormat(getFormat());
        }

        self.changeFormat = function(format) {
            var datetimePicker = jqDatetimePicker.data('DateTimePicker');
            //if (format.match(/\[GMT\]/)) {
            //    datetimePicker.locale(moment.locale('en'));
            //} else {
            //    datetimePicker.locale(moment.locale('zh-CN'));
            //}
            datetimePicker.format(getFormat(format));
        }

        self.changeTimestampUnit = function(timestampUnit) {
            if (self.datetime) {
                self.toTimestamp();
            } else if (self.timestamp) {
                self.timestamp = parseInt(self.timestamp * (timestampUnit == 'ms' ? 1000 : 1/1000));
            }
        }

        self.changeCustFormat = function(format) {
            if (!self.format) {
                self.changeFormat(format);
            }
        }

        self.toTimestamp = function() {
            self.timestamp = self.datetime ?
                    parseInt(self.datetime.format(self.timestampUnit == 'ms' ? 'x' : 'X'), 10) : null;
        }

        self.toDatetime = function() {
            var date = null, datetimeTo = '';
            if (self.timestamp) {
                var date = self.timestampUnit == 'ms' ? moment(self.timestamp) : moment.unix(self.timestamp);
                datetimeTo = date.format(getFormat());
            }
            jqDatetimePicker.data('DateTimePicker').date(date);
        }

        self.reset = function() {
            self.datetime = null;
            self.timestamp = null;
            self.timestampUnit = 'ms';
            self.timezone = 'Asia/Shanghai';
            self.format = '';
            self.custFormat = defaultFormat;
            self.changeFormat(defaultFormat);
            self.changeTimezone(self.timezone);
            jqDatetimePicker.data('DateTimePicker').date(null);
        }

        function getFormat(format) {
            if (format) {
                return format;
            } else if (self.format) {
                return self.format;
            } else if (self.custFormat) {
                return self.custFormat;
            } else {
                return defaultFormat;
            }
        }

        self.callback = function(height, width, refresh) {
            if (height < 515) {
                $('.clock').css({
                    'margin': '-10px auto -5px',
                    'transform': 'scale(0.8)',
                    '-moz-transform': 'scale(0.8)',
                    '-webkit-transform': 'scale(0.8)'
                });
            } else {
                $('.clock').css({
                    'margin': '30px auto 50px',
                    'transform': '',
                    '-moz-transform': '',
                    '-webkit-transform': ''
                });
            }
            $('form>.row:eq(2)').css({
                'height': Math.max(height - $('form>.row:eq(0)').height() - 85, 360) + 'px',
                'overflow-y': 'auto'
            });
            // Toolbar
            if (refresh) {
                $('.navbar-form').append($compile($('#opt-toolbar').html())($scope));
            }
        }
    });
});
